package com.xshang.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.xshang.io.Resource;
import com.xshang.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 使用dom4j+xpath解析配置文件，封装Config
     * @param inputStream
     * @return
     */
    public Configuration parse(InputStream inputStream) throws DocumentException {

        // 使用dom4j 的api获取配置文件的文档对象
        Document document = new SAXReader().read(inputStream);
        // 获取根标签
        Element rootElement = document.getRootElement();
        // 使用xpath表达式 获取所有property标签
        /*
            <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://192.168.1.5:3306/Test"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
         */
        List<Element> list = rootElement.selectNodes("//property");

        Properties properties = new Properties();
        for (Element element : list) {
            // 获取property标签name和value的值
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        // 创建数据源对象 (使用德鲁伊连接池  解决数据库链接频繁创建关闭的问题)
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getProperty("driverClassName"));
        druidDataSource.setUrl(properties.getProperty("url"));
        druidDataSource.setUsername(properties.getProperty("username"));
        druidDataSource.setPassword(properties.getProperty("password"));

        // 创建好的数据源对象封装到configuration对象中
        configuration.setDataSource(druidDataSource);

        // -------------解析映射配置文件
        // 1 获取映射配置文件的路径
        // 2 根据路径进行映射配置文件的加载解析
        // 3 封装到MappedStatement中 ----> configuration里面的map集合中
        // <mapper resource="mapper/UserMapper.xml"/>
        List<Element> mapElementList = rootElement.selectNodes("//mapper");
        for (Element element : mapElementList) {
            String mapperXmlPath = element.attributeValue("resource");
            InputStream resourceAsStream = Resource.getResourceAsStream(mapperXmlPath);
            // 解析映射配置文件的对象
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }

        return configuration;
    }
}
